package services

import (
	"encoding/json"
	"errors"
	"lingc/models"
	"lingc/utils"
	"time"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

// AuthHandleLogService 提供账号登录校验的服务
type AuthHandleLogService struct {
	DB *gorm.DB
}

// NewAuthHandleLogService 创建一个新的 AuthHandleLogService 实例
func NewAuthHandleLogService(db *gorm.DB) *AuthHandleLogService {
	return &AuthHandleLogService{DB: db}
}

//表单业务

/**
 * @Description: 分页获取权限组列表
 * @param where
 * @param page
 * @param pageSize
 * @return []*models.AuthHandleLog
 * @return int
 * @return int64
 * @return error
 */
func (s *AuthHandleLogService) PageAuthHandleLogList(where string, page, pageSize int) ([]*models.AuthHandleLogList, int, int64, error) {
	var groups []*models.AuthHandleLog
	var total int64

	// 计算偏移量
	offset := (page - 1) * pageSize

	// 获取总记录数
	if err := s.DB.Model(&models.AuthHandleLog{}).Where(where).Count(&total).Error; err != nil {
		return nil, 1, 0, err
	}

	// 获取分页数据
	if err := s.DB.Where(where).Preload("AuthUser").Offset(offset).Limit(pageSize).Order("id DESC").Find(&groups).Error; err != nil {
		return nil, 1, 0, err
	}
	var list []*models.AuthHandleLogList
	list = []*models.AuthHandleLogList{}
	for _, data := range groups {
		list = append(list, &models.AuthHandleLogList{
			ID:        data.ID,
			AdminID:   data.AdminID,
			AdminName: data.AuthUser.Username,
			Name:      data.Name,
			URL:       data.URL,
			Param:     data.Param,
			AppID:     data.AppID,
			CreatedAt: time.Unix(data.CreatedAt, 0).Format("2006-01-02 15:04:05"), // 格式化时间戳
			UpdatedAt: time.Unix(data.UpdatedAt, 0).Format("2006-01-02 15:04:05"), // 格式化时间戳
		})
	}

	return list, page, total, nil
}

/**
 * @Description: 创建新权限组
 * @param username
 * @param password
 * @param realname
 * @param avatar
 * @param status
 * @return *models.AuthHandleLogCreate
 * @return error
 */
func (s *AuthHandleLogService) CreateAuthHandleLog(data *models.AuthHandleLogCreate) (*models.AuthHandleLogCreate, error) {
	// 检查权限组名是否已存在
	addData := &models.AuthHandleLog{
		AdminID:   data.AdminID,
		AppID:     data.AppID,
		Name:      data.Name,
		Param:     data.Param,
		URL:       data.URL,
		CreatedAt: time.Now().Unix(),
		UpdatedAt: time.Now().Unix(),
	}
	// 保存新权限组到数据库
	if err := s.DB.Create(addData).Error; err != nil {
		return nil, err
	}
	return data, nil
}

// GetAuthHandleLog 获取权限组信息
func (s *AuthHandleLogService) GetAuthHandleLog(where string) (*models.AuthHandleLog, error) {
	var data models.AuthHandleLog
	if err := s.DB.Where(where).First(&data).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errors.New("权限组不存在")
		}
		return nil, err
	}
	// log.Printf("data_info:%v", data)
	return &data, nil
}

/**
 * @Description: 更新权限组信息
 * @param data
 * @return error
 */
func (s *AuthHandleLogService) UpdateAuthHandleLog(data *models.AuthHandleLogUpdate) (*models.AuthHandleLogUpdate, error) {
	// 检查权限组名是否已存在
	var existingUser models.AuthHandleLog
	if err := s.DB.Where("id = ?", data.ID).First(&existingUser).Error; err != nil {
		return nil, errors.New("数据不存在")
	}
	existingUser.Name = data.Name
	existingUser.URL = data.URL
	existingUser.Param = data.Param
	existingUser.UpdatedAt = time.Now().Unix()
	return data, s.DB.Save(existingUser).Error
}

/**
 * @Description: 删除权限组
 * @param id
 * @return error
 */
func (s *AuthHandleLogService) DeleteAuthHandleLog(id uint) error {
	var data models.AuthHandleLog
	if err := s.DB.Where("id = ?", id).First(&data).Error; err != nil {
		return errors.New("数据不存在")
	}
	return s.DB.Delete(&data).Error
}

/**
 * @Description: 批量删除权限组
 * @param id
 * @return error
 */
func (s *AuthHandleLogService) DeleteAuthHandleLogs(ids []string) error {
	var data models.AuthHandleLog
	for _, id := range ids {
		if err := s.DB.Where("id = ?", id).First(&data).Error; err != nil {
			return errors.New("数据不存在")
		}
		err := s.DB.Delete(&data).Error
		if err != nil {
			return errors.New("删除失败")
		}
	}
	return nil
}

// GetParentAllName 获取父级整条线的名称集合
func GetParentAllName(c *gin.Context, key string, mapUrl map[string]*models.AuthRuleMenusName) string {

	rulesMapPidStr := utils.GetRedis("auth_rule_map_pid")
	if rulesMapPidStr == "" {
		return ""
	}
	mapPid := make(map[int]string)
	err := json.Unmarshal([]byte(rulesMapPidStr), &mapPid)
	if err != nil {
		return ""
	}
	// log.Printf("父级mapPid：%v", mapPid)
	// log.Printf("父级mapUrl：%v", mapUrl)
	return GetNameStr(key, mapPid, mapUrl)
}

func GetNameStr(key string, mapPid map[int]string, mapName map[string]*models.AuthRuleMenusName) string {
	tpid := mapName[key].ParentID
	nameStr := mapName[key].Title
	tkey := mapPid[int(tpid)]
	// log.Printf("tkey：%v", tkey)
	// log.Printf("tpid：%v", tpid)
	// log.Printf("nameStr：%v", nameStr)
	if tpid != 0 {
		nameStr = GetNameStr(tkey, mapPid, mapName) + "->" + nameStr
	}
	return nameStr

}
